package com.taobao.snowsnow.web;

import java.util.Collections;
import java.util.List;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.taobao.snowsnow.hibernate.pojo.Shopper;
import com.taobao.snowsnow.hibernate.service.ShopperService;
import com.taobao.snowsnow.util.FetchMyleftInfo;

public class ShopperAction extends ActionSupport {
	private ShopperService shopperService;

	@Override
	public String execute() throws Exception {
		Shopper newer_shopper = new FetchMyleftInfo().getShopper();
		Shopper laster_shopper = shopperService.getLastObject();
		if(laster_shopper == null) {
			shopperService.create(newer_shopper);
		} else if(!newer_shopper.equals(laster_shopper)) {
			shopperService.create(newer_shopper);
		} else  {
			laster_shopper.setCredit(newer_shopper.getCredit());
			laster_shopper.setFavour(newer_shopper.getFavour());
			laster_shopper.setQuantity(newer_shopper.getQuantity());
			shopperService.saveOrUpdate(laster_shopper);
		}
		
		List<Shopper> shoppers = shopperService.findAll();
		Collections.reverse(shoppers);
		
		String nextLevelText = getNextLevelText(laster_shopper);
		int nextLevelVal = getNextLeveltVal(laster_shopper);
		
		ActionContext .getContext().getSession().put("shoppers", shoppers);
		ActionContext .getContext().getSession().put("nextLevelText", nextLevelText);
		ActionContext .getContext().getSession().put("nextLevelVal", nextLevelVal);
		
		return SUCCESS;
	}
	
	/**
	 * 获取下次等级的文本标识
	 * @return
	 * 		等级的文本标识
	 */
	private String getNextLevelText(Shopper laster_shopper) {
		return calcNextLevel(laster_shopper.getCredit())[0];
	}
	
	private int getNextLeveltVal(Shopper laster_shopper) {
		return Integer.valueOf(calcNextLevel(laster_shopper.getCredit())[1]);
	}
	
	/**
	 * 计算还差多少信誉升级
	 * @param credit
	 * @return
	 */
	private String[] calcNextLevel(int credit) {
		
		if(credit < 5000 && credit > 2000) {
			return new String[]{"5钻", "5000"};
		} else if(credit > 5000 && credit < 10000) {
			return new String[]{"1皇冠", "10000"};
		} else if(credit > 10000 && credit < 20000) {
			return new String[]{"2皇冠", "20000"};
		} else if(credit > 20000 && credit < 50000) {
			return new String[]{"3皇冠", "50000"};
		} else if(credit > 500000 && credit < 100000) {
			return new String[]{"4皇冠", "100000"};
		}  
		
		return null;
	}

	public ShopperService getShopperService() {
		return shopperService;
	}

	public void setShopperService(ShopperService shopperService) {
		this.shopperService = shopperService;
	}

	private static final long serialVersionUID = -6014408025331378132L;

}
